<?php
/**
 * Created by @baidu-aip
 * Author: ylang
 * Time: 2022/2/24 12:06
 */

namespace Hedgehog\BaiduAip;

use Hanson\Foundation\AbstractAPI;
use Hedgehog\BaiduAip\Api\AccessToken;
use Hedgehog\BaiduAip\Exception\Exception;

class Api extends AbstractAPI
{

    const DOMAIN = 'https://aip.baidubce.com/rest/2.0/';

    protected AccessToken $accessToken;


    public function __construct(AccessToken $accessToken)
    {
        $this->accessToken = $accessToken;
    }


    protected function parseJson(string $url, array $data = [])
    {
        $data['access_token'] = $this->accessToken->getToken();

        $result = json_decode($this->getHttp()->post(self::DOMAIN.$url, $data)->getBody(), true);
        $this->checkResultAndException($result);
        return $result;
    }


    protected function checkResultAndException($result):void
    {
        isset($result['error_code']) and Exception::error($result['error_msg'], $result['error_code']);
    }

}